#include "udphandler.h"
#include <QDebug>
#include <QBuffer>
#include <QByteArray>

UDPHandler::UDPHandler(QObject *parent)
    : QObject{parent}
{
    m_udpSendSocket = new QUdpSocket(this);
    m_udpReceiveSocket = new QUdpSocket(this);
}

// 把ImageDealer处理好的图片发出去
void UDPHandler::sendImage(const QImage image)
{
    // 1. 判断是否需要发送
    // ip是否有效
    if (m_targetAddress.isEmpty())
    {
        qDebug() << "ip为空";
        return;
    }
    // 图片是否有效
    if (image.isNull()) {
        qWarning() << "Failed to load image!";
        return;
    }
    // 1. 将QImage转换为QByteArray
    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    buffer.open(QIODevice::WriteOnly);
    image.save(&buffer, "JPEG", 10);
    // image.save(&buffer, "PNG");  // 使用 PNG 格式，保证完整性

    // 3. 发送数据
    QHostAddress targetIP(m_targetAddress);
    m_udpSendSocket->writeDatagram(byteArray, targetIP, m_targetPort);
    qDebug() << "图片大小" << byteArray.size();
}

// 设置对方Ip
void UDPHandler::onGetFriendIp(const QString userId, const QString friendId, const QString friendIp)
{
    qDebug() << "设置朋友信息";
    m_userId = userId;
    m_friendId = friendId;
    m_targetAddress = friendIp;
    // 通过50000端口接受数据
    int BASE_PORT = 50000;
    m_targetPort = BASE_PORT + m_friendId.toInt();
    m_listenPort = BASE_PORT + m_userId.toInt();
    qDebug() << m_targetPort << m_listenPort;
    m_udpReceiveSocket->bind(QHostAddress::Any, m_listenPort);
    connect(m_udpReceiveSocket, &QUdpSocket::readyRead, this, &UDPHandler::receiveData);
}

// m_udpReceiveSocket收到数据
void UDPHandler::receiveData()
{
    qDebug() << "receiveData from socket";
    while (m_udpReceiveSocket->hasPendingDatagrams())
    {
        QByteArray buffer;
        buffer.resize(m_udpReceiveSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        m_udpReceiveSocket->readDatagram(buffer.data(), buffer.size(), &sender, &senderPort);
        QImage image;
        // 使用 QImage 构造函数从 QByteArray 载入图像数据
        image.loadFromData(buffer);
        if (!image.isNull())
        {
            emit receiveImage(image);
            qDebug() << "Received image" << sender.toString() << ":" << senderPort;
            return;
        }
        qDebug() << "convert to image failed";
    }
}
